package com.example.controller;

import com.example.po.User;
import com.example.service.UserService;
import com.example.utils.CheckCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 进入WEB-INF中的登录页面
 */
@Controller
public class UserController {
    @Autowired
    private CheckCode checkCode;
    @Autowired
    private UserService userService;

    /**
     * 判断是否可以登录
     * @param user
     * @param code
     * @param session
     * @return 如果成功返回主页面,否则返回失败页面
     */
   @RequestMapping("/isLogin")
    public String isLogin(User user, String code, HttpSession session){
       if(!"1234".equals(code)){//验证码有误
           session.setAttribute("title","登录失败");
           session.setAttribute("msg","验证码错误");
           return "/fail";
       }else if(!userService.findUser(user,session)){//输入用户名或密码有误
           session.setAttribute("title","登录失败");
           session.setAttribute("msg","用户名或密码有误");
           return "/fail";
       }else{
           return "/main";
       }
    }

    /**
     * 获取验证码,并将验证码存到session的属性code里
     * @param request
     * -
     * @param response
     */
    @ResponseBody
    @RequestMapping("/getCode")
    public void getCheckCode(HttpServletRequest request, HttpServletResponse response){
       checkCode.getCheckCode(request,response);
    }

    @ResponseBody
    @RequestMapping("/updateUserPwd")
    public String updateUserPwd(User user,HttpSession session){
        session.setAttribute("user",user);
        if(userService.updateUserPassword(user)){
            return "OK";
        }else{
            return "error";
        }
    }
}
